package server

import (
	"encoding/json"
	"fmt"
	"net"
	"net/http"
)

// 读取完整消息的方法
func readMessage(conn net.Conn) ([]byte, error) {
	// 首先读取4个字节，表示消息的长度
	header := make([]byte, 4)
	_, err := conn.Read(header)
	if err != nil {
		return nil, err
	}

	// 解析消息长度（假设是固定长度的 4 字节整数）
	messageLength := int(header[0])<<24 | int(header[1])<<16 | int(header[2])<<8 | int(header[3])

	// 读取完整的消息
	buffer := make([]byte, messageLength)
	_, err = conn.Read(buffer)
	if err != nil {
		return nil, err
	}

	return buffer, nil
}

func handleConnection(conn net.Conn) {
	defer conn.Close()
	fmt.Println("客户端已连接:", conn.RemoteAddr())

	for {
		// 读取完整的消息
		message, err := readMessage(conn)
		if err != nil {
			fmt.Println("读取消息失败:", err)
			return
		}

		var req map[string]string
		err = json.Unmarshal(message, &req)
		if err != nil {
			conn.Write([]byte(`{"error":"invalid json"}`))
			fmt.Printf("error: %+v | %s", err, string(message))
			continue
		}

		// 处理请求
		path := req["path"]
		switch path {
		case "/greatInfo":
			info := GetHostData()
			resp, _ := json.Marshal(info)
			conn.Write(resp)

		default:
			conn.Write([]byte(`{"error":"unknown path"}`))
		}
	}
}

// 处理 WebSocket 连接
func handleWebSocket(w http.ResponseWriter, r *http.Request) {
	conn, err := upgrader.Upgrade(w, r, nil)
	if err != nil {
		fmt.Println("WebSocket 升级失败:", err)
		return
	}
	defer conn.Close()

	fmt.Println("客户端已连接:", conn.RemoteAddr())

	for {
		// 读取客户端发送的消息
		messageType, p, err := conn.ReadMessage()
		if err != nil {
			fmt.Println("读取消息失败:", err)
			return
		}

		var req map[string]string
		err = json.Unmarshal(p, &req)
		if err != nil {
			conn.WriteMessage(messageType, []byte(`{"error":"invalid json"}`))
			fmt.Printf("error: %+v | %s", err, string(p))
			continue
		}

		// 处理请求
		path := req["path"]
		switch path {
		case "/greatInfo":
			info := GetHostData()
			resp, _ := json.Marshal(info)
			conn.WriteMessage(messageType, resp)

		default:
			conn.WriteMessage(messageType, []byte(`{"error":"unknown path"}`))
		}
	}
}
